package com.hmall.item.test;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.item.domain.po.Item;
import com.hmall.item.service.IItemService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class InitData {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private IItemService itemService;

    @Test
    public void testBulkDoc() throws IOException {
        int pageNum = 1;

        while (true) {
            //分页查询数据库所有内容
            //设置分页参数
            Page<Item> page = new Page<>(pageNum++, 1000);

            //设置业务参数
            LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Item::getStatus, 1);
            //执行分页参数
            page = itemService.page(page, wrapper);
            //处理分页结果
            if (CollUtil.isEmpty(page.getRecords())) {
                System.out.println("数据同步完毕");
                return;
            }
            //保存到ES
            //1.创建请求对象
            BulkRequest bulkRequest = new BulkRequest("hmall");

            //2.设置请求参数(新增或修改)
            for (Item item : page.getRecords()) {
                IndexRequest indexRequest = new IndexRequest("hmall").id(item.getId().toString());
                indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            //3.发送请求
            client.bulk(bulkRequest, RequestOptions.DEFAULT);

            //4.处理返回结果(只有查询需要返回结果)
        }

    }
}
